package cn.itlaobing.web.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.itlaobing.vo.PageRequest;
import cn.itlaobing.web.controller.AController;


@WebServlet("/")
public class DispatcherServlet extends HttpServlet {
	
	Log log=LogFactory.getLog(DispatcherServlet.class);

	
	/**
	 *  往PageRequest对象中 添加查询条件,这些查询条件从HttpServletRequest中获取
	 * @param pageRequest
	 * @param req
	 */
	private void buildPageRequestSearchFilter(PageRequest pageRequest,HttpServletRequest req){
		//获取所有的请求参数    name=zhangsan
		Map<String, String[]> parameterMap=req.getParameterMap();
		
		for (Map.Entry<String,String[]> entry : parameterMap.entrySet()) {			
			//FIXME 对于同一个参数名称有多个值的情况需要考虑
			//扔掉空值
			if(StringUtils.isNoneBlank(entry.getValue()[0])){
				pageRequest.addSerachFilter(entry.getKey(), entry.getValue()[0]);
			}
		}
	}
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		//获取页码
				String pageNumber=req.getParameter(PageRequest.PAGE_NUMBER_PARAM);
				//获取页大小
				String pageSize=req.getParameter(PageRequest.PAGE_SIZE_PARAM);
				PageRequest pr=new PageRequest();
				//创建PageRequest对象
				if(StringUtils.isNotBlank(pageNumber)){
					pr.setPageNumber(Long.parseLong(pageNumber));
					if(StringUtils.isNotBlank(pageSize)){
						pr.setPageSize(Long.parseLong(pageSize));
					}
				}
				
				//获取查询条件
				buildPageRequestSearchFilter(pr,req);
				//将PageRequest对象放到 request范围
				req.setAttribute(PageRequest.REQUEST_SCOPE_KEY, pr);

				//获取ServletContext对象
				ServletContext ctx=this.getServletContext();
				//获取Spring容器
				WebApplicationContext wctx=WebApplicationContextUtils.getWebApplicationContext(ctx);
				
				//获取请求地址
				String requestUrl=req.getServletPath();
				//因为请求地址就是 Controller对象在spring容器中的标识，所以我们可以通过 请求的地址获取Controller对象
				//保存到范围中，页面中会用到
				req.setAttribute("requestPath",req.getContextPath()+requestUrl);
				AController controller;
				try {
					controller = wctx.getBean(requestUrl,AController.class);
					String method=req.getMethod();
					 if (method.equals("GET")) {
						 controller.doGet(req, resp); 

			        } else if (method.equals("POST")) {
			        	controller.doPost(req, resp); 

			        } else {
			            String errMsg ="错误的请求方式";
			            resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
			        }
				} catch (BeansException e) {				
					e.printStackTrace();
					resp.sendError(HttpServletResponse.SC_NOT_FOUND,"请求地址不存在");
				}				
	}
	
}
